﻿using System;
using System.IO;
using LitJson;
using Newtonsoft.Json;

public class GeJSON{

    #region 文件处理

    /// <summary>
    /// 读取JSON文件，path文件路径(不需加Json扩展名), 返回JsonData
    /// </summary>
    public static JsonData LoadJson(string path, Action<JsonData> callBack)
    {
        string file = ReadText(path);
        JsonData jsonD = JsonMapper.ToObject(file);
        callBack(jsonD);
        return jsonD;
    }

    /// <summary>
    /// 保存JSON文件, path路径(不需加Json扩展名), data数据
    /// </summary>
    public static void SaveJson(string path, JsonData data)
    {
        StreamWriter sw = File.CreateText(@"./Assets/" + path);//创建一个用于写入 UTF-8 编码的文本  
        string JsonStr = data.ToJson();
        JsonStr = FormatJson(JsonStr);
        sw.WriteLine(JsonStr);//以行为单位写入字符串  
        sw.Close();
        sw.Dispose();//文件流释放
    }

    /// <summary>
    /// 格式化输出Json
    /// </summary>
    static public string FormatJson(string jsonContent)
    {
        //格式化json字符串
        JsonSerializer serializer = new JsonSerializer();
        TextReader tr = new StringReader(jsonContent);
        JsonTextReader jtr = new JsonTextReader(tr);
        object obj = serializer.Deserialize(jtr);
        if (obj != null)
        {
            StringWriter textWriter = new StringWriter();
            JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
            {
                Formatting = Formatting.Indented,
                Indentation = 4,
                IndentChar = ' '
            };
            serializer.Serialize(jsonWriter, obj);
            return textWriter.ToString();
        }
        else
        {
            return jsonContent;
        }
    }

    public static string ReadText(string path)
    {
        // 当前文件路径"./" (如果是@"../"父级目录)
        string strReadFilePath = @"./Assets/" + path;
        StreamReader srReadFile = new StreamReader(strReadFilePath);
        string strReadLine = "";
        // 读取流直至文件末尾结束
        while (!srReadFile.EndOfStream)
        {
            strReadLine += srReadFile.ReadLine(); //读取每行数据
            Console.WriteLine(strReadLine); //屏幕打印每行数据
        }
        // 关闭读取流文件
        srReadFile.Close();
        return strReadLine;
    }
    #endregion
}
